//
//  OAuthViewController.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/10.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    lazy var webView = UIWebView()
   override func loadView() {
        view = webView
    webView.delegate = self
    
    title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")

    }
    
    //关闭moda上来的界面
    func close() {
        //moda界面被关闭， SVProgressHUD.dismiss()。也要关闭它
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //请求
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetWorkingTools.sharedTools.oauthUrl()))
    
    }
//    UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
       SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //1 如果请求的URL包含 回调地址，需要判断参数，否则继续加载
    //2 如果请求的参数中包含code 可以从请求的url中获取请求码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlstring  = request.URL!.absoluteString
        //判断是否包含回调地址
        if !urlstring.hasPrefix(NetWorkingTools.sharedTools.redirectUrl){
            return true
        }
     
        if let query = request.URL?.query where query.hasPrefix("code=") {
            print("huo qu ")
            
            let code = query.substringFromIndex("code=".endIndex)
            print("获取授权码" + code)
          
          loadAccessToken(code)
            close()
            
        }else {
            close()
        }
        return false
    }
    
    private func loadAccessToken(code:String) {
        
        NetWorkingTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil
            {
         self.netError()
         return
    }
            
        //字典转模型
        UserAccount(dict: result!).loadUserInfo({ (error) -> () in
            if error != nil{ 
//                self.netError()
                return
            }
//              // 发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(GFRootViewCotrollerSwitchNotification, object: false)
               //关闭控制器
               self.close()
            })
        }
    }
    deinit{
        print("886")
    }
    //网络错误处理
    private func netError() {
        SVProgressHUD.showInfoWithStatus("网络不给力")
        //y延时关闭
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(time, dispatch_get_main_queue()) {
            
            self.close()
        }
    }
}
